package profile

import (
	"context"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	utilx "mall/common/utils/user"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserAccountLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetUserAccountLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserAccountLogic {
	return &GetUserAccountLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetUserAccountLogic) GetUserAccount(
	req *types.GetUserAccountReq,
	headers *[]*types.Header,
) (*types.UserAccountInfo, error) {
	userId := jwt.GetUserId(l.ctx)
	if userId > 0 {
		var platform string
		if req.AuthType == nil || len(strings.TrimSpace(*req.AuthType)) == 0 {
			platform = globalkey.UserAuthTypeWechatMini
		} else {
			platform = *req.AuthType
		}
		platformId := utilx.GetThirdPartyPlatformId(platform)
		if platformId == 0 {
			return nil, resultx.NewErrCode(resultx.USER_AUTH_PARAM_INVALID)
		}

		res, err := l.svcCtx.UserRpc.GetUserAccount(l.ctx, &userclient.GetUserReq{
			PlatformId: pointy.GetPointer(platformId),
			UserId:     pointy.GetPointer(userId),
		})
		if err != nil {
			return nil, err
		}

		return &types.UserAccountInfo{
			Integral: res.AvailablePoint,
			Growth:   res.HistoryPoint,
			Gems:     res.AvailableBalance,
			RankId:   res.RankId,
		}, nil
	}

	return &types.UserAccountInfo{}, nil
}
